require("../db/index");
const { UserModel } = require("../db/model/index");
const { query, execute } = require("../db/dbType/mysql");
const {
  insertPayload,
  updatePayload,
  queryPayload,
} = require("../utils/queryPayload");

const UserService_mongodb = {
  getUser: () => {
    return UserModel.find();
  },
  addUser: (data) => {
    return UserModel.create(data);
  },
  updateUser: (id, data) => {
    return UserModel.findByIdAndUpdate(id, data);
  },
  delUser: (id) => {
    return UserModel.findByIdAndDelete(id);
  },
};

const UserService_mysql = {
  getUser: async (data) => {
    const { props, values } = queryPayload(data, ["name"]);

    const sql = `select * from students where ${props}`;
    const res = await query(sql, values);
    return res.error ? new Error(res.error) : res.data;
  },
  addUser: async (data) => {
    const { props, labels, values } = insertPayload(data);

    const sql = `insert into students(${props}) values(${labels})`;
    const res = await query(sql, values);
    return res.error ? new Error(res.error) : null;
  },
  updateUser: async (id, data) => {
    const { props, values } = updatePayload(data);

    const sql = `update students set ${props} where id = ?`;
    const payload = values.concat(id);
    const res = await query(sql, payload);
    return res.error ? new Error(res.error) : null;
  },
  delUser: async (id) => {
    const findUser = await UserService_mysql.getUser({ id });
    if (!findUser || findUser.length === 0) {
      return new Error("此用户不存在");
    }
    const sql = "delete from students where id = ?";
    const res = await query(sql, [id]);
    return res.error ? new Error(res.error) : null;
  },
};

switch (process.env.NODE_ENV_DB_TYPE) {
  case "mysql":
    module.exports = UserService_mysql;
    break;
  case "mongodb":
    module.exports = UserService_mongodb;
    break;
  default:
    module.exports = UserService_mongodb;
}
